package com.tree.rw.demo.aop;

import com.tree.rw.demo.bean.DBContextHolder;
import com.tree.rw.demo.enums.DBTypeEnum;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * @ClassName com.tree.rw.demo.aop
 * Description: <类功能描述>. <br>
 * <p>
 * <使用说明>
 * </p>
 * @Author tree
 * @Date 2019-06-02 14:37
 * @Version 1.0
 */
@Aspect
@Component
public class DataSourceAop {

    /**
     *
     */
    @Pointcut("!@annotation(com.tree.rw.demo.annotation.Master) "+
            "&& (" +
            "execution(* com.tree.rw.demo.mapper..*.get*(..))" +
         "|| execution(* com.tree.rw.demo.mapper..*.select*(..))" +
            ") ")
    public void readPoint(){

    }

    /**
     *
     */
    @Pointcut("@annotation(com.tree.rw.demo.annotation.Master) "+
            "|| execution(* com.tree.rw.demo.mapper..*.insert*(..))" +
            "|| execution(* com.tree.rw.demo.mapper..*.add*(..))" +
            "|| execution(* com.tree.rw.demo.mapper..*.update*(..))" +
            "|| execution(* com.tree.rw.demo.mapper..*.edit*(..))" +
            "|| execution(* com.tree.rw.demo.mapper..*.delete*(..))" +
            "|| execution(* com.tree.rw.demo.mapper..*.remove*(..))"
            )
    public void writePoint(){

    }

    @Before("writePoint()")
    public void write(JoinPoint joinPoint){
        DBContextHolder.setDataSource(DBTypeEnum.MASTER);
    }

    @Before("readPoint()()")
    public void read(JoinPoint joinPoint){
        DBContextHolder.setDataSource(DBTypeEnum.SLAVE1);
    }

    /**
     * 另一种写法：if...else...  判断哪些需要读从数据库，其余的走主数据库
     */
//    @Before("execution(* com.cjs.example.service.impl.*.*(..))")
//    public void before(JoinPoint jp) {
//        String methodName = jp.getSignature().getName();
//
//        if (StringUtils.startsWithAny(methodName, "get", "select", "find")) {
//            DBContextHolder.roundSlave();
//        }else {
//            DBContextHolder.master();
//        }
//    }
}
